package main

import (
	"fmt"
	"sync"
	"time"
)

var (
	x      int
	wg     sync.WaitGroup
	muLock sync.Mutex   // 互斥锁
	rwlock sync.RWMutex // 读写锁
)

func read() {
	//muLock.Lock()
	rwlock.RLock() // 加读锁
	time.Sleep(time.Millisecond)
	//muLock.Unlock()
	rwlock.RUnlock() // 解读锁
	wg.Done()
}

func write() {
	//muLock.Lock()
	rwlock.Lock() // 加互斥锁
	x += 1
	time.Sleep(time.Millisecond * 10)
	//muLock.Unlock()
	rwlock.Unlock() // 解互斥锁
	wg.Done()
}

func main() {
	startTime := time.Now()
	for i := 0; i < 1000; i++ {
		wg.Add(1)
		go read()
	}

	for i := 0; i < 10; i++ {
		wg.Add(1)
		go write()
	}
	wg.Wait()
	endTime := time.Now()
	fmt.Println("程序耗时：", endTime.Sub(startTime))
}
